package com.huwaiwai.ssl;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.util.Base64Utils;

import javax.net.ssl.SSLContext;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import static org.apache.http.conn.ssl.NoopHostnameVerifier.INSTANCE;

public class SSLHttpClient {

    public static void main(String[] args) throws IOException {
        String url = "https://202.108.57.16:30500/credits/add?uid=4895&credits=25&sign=a35412aff215c8ab2f0ac5fd0a6aed09&orderNum=104092666445877C0057&description=活动积分奖励&appKey=46cHDo7yrQ9Ermd3Un7XC6tAskjA&type=virtual&timestamp=1562756359";
//        String url = "https://202.108.57.16:30500/credits/consume?actualPrice=0&ip=testIp&sign=06d7f1141ee714c535d71b0ba4c2734d&orderNum=order-for-test-1557899257821&description=%E6%B5%8B%E8%AF%95%E4%B8%93%E7%94%A8%E5%AE%9E%E7%89%A9&waitAudit=true&type=object&params=%E8%96%87%E8%96%87%3A17822111111%3A%E6%B5%99%E6%B1%9F%E7%9C%81%3A%E6%9D%AD%E5%B7%9E%E5%B8%82%3A%E8%A5%BF%E6%B9%96%E5%8C%BA%3A%E6%96%87%E4%B8%80%E8%A5%BF%E8%B7%AF98%E5%8F%B7&uid=001&credits=1000&facePrice=0&appKey=jlg88lyxz7siqtmr&timestamp=1557899257821&paramsTest62=62";
//        String url = "https://202.108.57.16:30500/credits/add?uid=002&credits=500&ip=testIp&sign=c62074713de3f8a3033479b1c104a77d&orderNum=order-for-test-1557899675830&description=%E6%B8%B8%E6%88%8F%E5%8A%A0%E7%A7%AF%E5%88%86%E6%8E%A5%E5%8F%A3%E6%B5%8B%E8%AF%95&appKey=jlg88lyxz7siqtmr&type=game&timestamp=1557899675830";
        SSLContext sslContext = getSSLContext("E:\\ideaProjects\\java-normal\\src\\main\\resources\\njsjyh.keystore", "duiba2zx");
        assert sslContext != null;
        RegistryBuilder<ConnectionSocketFactory> connectionSocketFactoryRegistryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
        connectionSocketFactoryRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
        connectionSocketFactoryRegistryBuilder.register("https", new SSLConnectionSocketFactory(sslContext, INSTANCE));
        Registry<ConnectionSocketFactory> socketFactoryRegistry = connectionSocketFactoryRegistryBuilder.build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

        //创建自定义的httpclient对象
        CloseableHttpClient client = HttpClients.custom()
                .setConnectionManager(connManager)
                .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, INSTANCE))
                .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(2000).build()).build();

        //创建post方式请求对象
        HttpGet httpGet= new HttpGet(url);
        httpGet.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpGet);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            String body = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
            System.out.println(body);
        }
        //释放链接
        response.close();
    }

    private static SSLContext getSSLContext(String keyStorePath, String password) {
        String base64 = "/u3+7QAAAAIAAAABAAAAAgAHenh0ZXN0MQAAAWqwERBnAAVYLjUwOQAAAkwwggJIMIIBsaADAgECAgQcthq0MA0GCSqGSIb3DQEBCwUAMFcxCzAJBgNVBAYTAmNuMQswCQYDVQQIEwJiajELMAkGA1UEBxMCYmoxDjAMBgNVBAoTBWNpdGljMQ4wDAYDVQQLEwVjaXRpYzEOMAwGA1UEAxMFY2l0aWMwHhcNMTcwOTExMDY1OTI0WhcNMjcwOTA5MDY1OTI0WjBXMQswCQYDVQQGEwJjbjELMAkGA1UECBMCYmoxCzAJBgNVBAcTAmJqMQ4wDAYDVQQKEwVjaXRpYzEOMAwGA1UECxMFY2l0aWMxDjAMBgNVBAMTBWNpdGljMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHK5QW6I2Qv7UY8MLGB4VE2ZyKCkfwbvdJirBC/jn06yuNWyURMIoWV1FMV5Q7YGUDFuPE0PcePVFfhPuiPBqYKIefyeEvc8NWJjzwdHu7cavlszqDQ5iE0vE4TO4Z8CJ4P66AJ59Txpy2mUQKYdJzmyNP8n9DEyX7I4OK2FK8xwIDAQABoyEwHzAdBgNVHQ4EFgQUkEqulag7H3FFEtOju3XCR/gCJcowDQYJKoZIhvcNAQELBQADgYEAZOqSNw5yhcdXI+Xvljyes4QHQLjWGi/jrpGw1N/T2kw6xLfD5ojN5F+aq3JolmrWd+bmE+O7mcb4KMVtSLWYADhHn2yCd0VWEOwKWgm1VjqQaSCTIyUdru2ciQGpsH1uDAunKC30KNIIJHxYxR7fvXAtjpa4aoN9d1c4tL0xY5l0BCwDFZl1B5O+PCoi1+vo214/kQ==";
        try (InputStream inputStream = new ByteArrayInputStream(Base64Utils.decodeFromString(base64))) {
            KeyStore keyStore = KeyStore.getInstance("jks");
            keyStore.load(inputStream, password.toCharArray());

            return SSLContexts.custom().loadTrustMaterial(keyStore, new TrustSelfSignedStrategy()).build();
        } catch (IOException
                | KeyStoreException
                | CertificateException
                | NoSuchAlgorithmException
                | KeyManagementException e) {
            e.printStackTrace();
            return null;
        }

    }
}
